package com.azhon.appupdate.service;

import com.azhon.appupdate.base.BaseHttpDownloadManager;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.azhon.appupdate.manager.HttpDownloadManager;
import com.azhon.appupdate.utils.*;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 项目名:    AppUpdate
 * 包名       com.azhon.appupdate.service
 * 文件名:    DownloadService
 * 创建时间:  2018/1/27 on 13:22
 * 描述:     TODO apk 下载服务
 *
 * @author 阿钟
 */


public final class DownloadService extends Ability implements OnDownloadListener {

    private static final String TAG = Constant.TAG + "DownloadService";
    private int smallIcon;
    private String apkUrl;
    private String apkName;
    private String downloadPath;
    private List<OnDownloadListener> listeners;
    private boolean showNotification;
    private boolean showBgdToast;
    private boolean jumpInstallPage;
    private boolean usePlatform;
    private int lastProgress;
    private DownloadManager downloadManager;
    private BaseHttpDownloadManager httpManager;
    private static final int MAX = 100;

    @Override
    public void onCommand(Intent intent, boolean flags, int startId) {
        init();
        super.onCommand(intent, flags, startId);
    }


    public void init() {
        downloadManager = DownloadManager.getInstance();
        if (downloadManager == null) {
            LogUtil.d(TAG, "init DownloadManager.getInstance() = null ,请先调用 getInstance(Context context) !");
            return;
        }
        apkUrl = downloadManager.getApkUrl();
        apkName = downloadManager.getApkName();
        downloadPath = downloadManager.getDownloadPath();
        smallIcon = downloadManager.getSmallIcon();
        //创建apk文件存储文件夹
        FileUtil.createDirDirectory(downloadPath);
        UpdateConfiguration configuration = downloadManager.getConfiguration();
        listeners = configuration.getOnDownloadListener();
        showNotification = configuration.isShowNotification();
        showBgdToast = configuration.isShowBgdToast();
        jumpInstallPage = configuration.isJumpInstallPage();
        usePlatform = configuration.isUsePlatform();
        //获取app通知开关是否打开
        boolean enable = false;
        try {
            enable = NotificationUtil.notificationEnable();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        LogUtil.d(TAG, enable ? "应用的通知栏开关状态：已打开" : "应用的通知栏开关状态：已关闭");
        if (checkApkMD5()) {
            LogUtil.d(TAG, "文件已经存在直接进行安装");
            //直接调用完成监听即可
            done(FileUtil.createFile(downloadPath, apkName));
        } else {
            LogUtil.d(TAG, "文件不存在开始下载");
            download(configuration);
        }
    }

    /**
     * 校验Apk是否已经下载好了，不重复下载
     *
     * @return 是否下载完成
     */
    private boolean checkApkMD5() {
        if (FileUtil.fileExists(downloadPath, apkName)) {
            String fileMD5 = FileUtil.getFileMD5(FileUtil.createFile(downloadPath, apkName));
            return fileMD5.equalsIgnoreCase(downloadManager.getApkMD5());
        }
        return false;
    }

    /**
     * 获取下载管理者
     */
    private synchronized void download(UpdateConfiguration configuration) {
        if (downloadManager.isDownloading()) {
            LogUtil.e(TAG, "download: 当前正在下载，请务重复下载！");
            return;
        }
        httpManager = configuration.getHttpManager();
        //使用自己的下载
        if (httpManager == null) {
            httpManager = new HttpDownloadManager(downloadPath);
            configuration.setHttpManager(httpManager);
        }
        //如果用户自己定义了下载过程
        httpManager.download(apkUrl, apkName, this);
        downloadManager.setState(true);
    }

    private PixelMap getLittleIcon() {
        Resource resource = null;
        try {
            resource = getResourceManager().getResource(smallIcon);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        ImageSource imageSource = ImageSource.create(resource, null);
        return imageSource.createPixelmap(null);
    }

    @Override
    public void start() {
        if (showNotification) {
            if (showBgdToast) {
                handler.sendEvent(0);
            }
            String startDownload = "开始下载";
            String startDownloadHint = "可稍后查看下载进度";
            NotificationUtil.showNotification(startDownload, startDownloadHint, getLittleIcon());
        }
        handler.sendEvent(1);
    }

    @Override
    public void downloading(int progress) {
        LogUtil.i(TAG, "max: " + MAX + " --- progress: " + progress);
        if (showNotification) {
            //优化通知栏更新，减少通知栏更新次数
            int curr = progress;
            if (curr != lastProgress) {
                lastProgress = curr;
                String downloading = "正在下载新版本";
                String content = curr < 0 ? "" : curr + "%";
                NotificationUtil.showProgressNotification(downloading, content, curr, MAX, getLittleIcon());
            }
        }
        InnerEvent event = InnerEvent.get(2, progress);
        handler.sendEvent(event);
    }

    @Override
    public void done(File apk) {
        LogUtil.d(TAG, "done: 文件已下载至" + apk.toString());
        downloadManager.setState(false);
        String downloadCompleted = "下载完成";
        String clickHint = "点击进行安装";
        NotificationUtil.showDoneNotification(downloadCompleted,
                clickHint, Constant.AUTHORITIES, apk);
        if (jumpInstallPage) {
            ApkUtil.installApk(getContext(), Constant.AUTHORITIES, apk);
        }
        //如果用户设置了回调 则先处理用户的事件 在执行自己的
        InnerEvent event = InnerEvent.get(3, apk);
        handler.sendEvent(event);
    }

    @Override
    public void cancel() {
        downloadManager.setState(false);
        if (showNotification) {
            NotificationUtil.cancelNotification();
        }
        handler.sendEvent(4);
    }

    @Override
    public void error(Exception e) {
        LogUtil.e(TAG, "error: " + e);
        HttpUtil.postException(this, usePlatform, apkUrl, e.toString(), HiLog.getStackTrace(e));
        downloadManager.setState(false);
        if (showNotification) {
            String downloadError = "下载出错";
            String conDownloading = "点击继续下载";
            NotificationUtil.showErrorNotification(getContext(), downloadError, conDownloading, getLittleIcon());
        }
        InnerEvent event = InnerEvent.get(5, e);
        handler.sendEvent(event);
    }


    private EventHandler handler = new MyEventHandler(EventRunner.getMainEventRunner());

    private final class MyEventHandler extends EventHandler {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }

        // 重写实现processEvent方法
        @Override
        public void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            int eventId = event.eventId;
            switch (eventId) {
                case 0:
                    new ToastDialog(getContext()).setText("正在后台下载新版本…").show();
                    break;
                case 1:
                    for (OnDownloadListener listener : listeners) {
                        listener.start();
                    }
                    break;
                case 2:
                    for (OnDownloadListener listener : listeners) {
                        listener.downloading((int) event.param);
                    }
                    break;
                case 3:
                    for (OnDownloadListener listener : listeners) {
                        listener.done((File) event.object);
                    }
                    downloadManager.setCanStart(true);
                    //执行了完成开始释放资源
                    releaseResources();
                    break;
                case 4:
                    for (OnDownloadListener listener : listeners) {
                        listener.cancel();
                    }
                    downloadManager.setCanStart(true);
                    //执行了完成开始释放资源
                    releaseResources();
                    break;
                case 5:
                    for (OnDownloadListener listener : listeners) {
                        listener.error((Exception) event.object);
                    }
                    downloadManager.setCanStart(true);
                    //执行了完成开始释放资源
                    releaseResources();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 下载完成释放资源
     */

    private void releaseResources() {
        if (handler != null) {
            handler.removeAllEvent();
        }
        if (httpManager != null) {
            httpManager.release();
        }
        terminateAbility();
        downloadManager.release();
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return null;
    }
}